package com.sample.library.portlet.search.category;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;

import com.liferay.portal.kernel.dao.search.SearchContainer;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.ParamUtil;
import com.sample.library.model.Category;
import com.sample.library.portlet.helper.ASComparator;
import com.sample.library.portlet.search.BookSearch;

public class CategorySearch extends SearchContainer<Category> {

	static List<String> headerNames = new ArrayList<String>();
	static Map<String, String> orderableHeaders = new HashMap<String, String>();
	
	static {
		headerNames.add("Category.Name");
		headerNames.add("Category.Description");
		orderableHeaders.put("name", "Category.Name");
	}

	public static final String EMPTY_RESULTS_MESSAGE = "no-users-were-found";

	public CategorySearch(PortletRequest portletRequest, PortletURL iteratorURL) {
		this(portletRequest, DEFAULT_CUR_PARAM, iteratorURL);
	}

	public CategorySearch(
			PortletRequest portletRequest, String curParam, PortletURL iteratorURL) {
		super(
			portletRequest, new CategoryDisplayTerms(portletRequest),
			new CategorySearchTerms(portletRequest), curParam, DEFAULT_DELTA,
			iteratorURL, headerNames, EMPTY_RESULTS_MESSAGE);
		
		CategoryDisplayTerms displayTerms = (CategoryDisplayTerms)getDisplayTerms();
		
		iteratorURL.setParameter(CategoryDisplayTerms.NAME, String.valueOf(displayTerms.getName()));
		
		try{
			String orderByCol = ParamUtil.getString(portletRequest, "orderByCol");
			String orderByType = ParamUtil.getString(portletRequest, "orderByType");
			OrderByComparator orderByComparator =getCategoryOrderByComparator(orderByCol, orderByType);
	
			setOrderableHeaders(orderableHeaders);
			setOrderByCol(orderByCol);
			setOrderByType(orderByType);
			setOrderByComparator(orderByComparator);
		}
		catch(Exception e){
			System.out.println("Loi roi!");
			_log.error(e.getMessage());
		}
	}
	
	private OrderByComparator getCategoryOrderByComparator(String orderByCol,
			String orderByType) {
		
		OrderByComparator orderByComparator = null;
		if(orderByCol.equals("name")) {
			orderByComparator = new ASComparator("name");
		}
		else {
			orderByComparator = new ASComparator("name");
		}
		
		return orderByComparator;
	}

	private static Log _log = LogFactoryUtil.getLog(BookSearch.class);
}
